package com.ng.biz.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.ng.common.annotation.TokenRequired;
import com.ng.common.annotation.Tx;
import com.ng.common.controller.Controller;
import com.ng.common.model.response.R;
import com.ng.common.timer.DataTaskTimer;
import com.ng.common.util.UuidUtil;
import com.ng.biz.model.domain.HttpApi;
import com.ng.biz.service.IHttpApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

@Tag(name = "HTTP数据管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("/biz/http")
public class HttpApiController extends Controller {
	
	@Autowired
	private IHttpApi httpAPIImpl;
	
	 @Autowired
	 private DataTaskTimer dataTaskTimer;

    // 提取常量
    private static final String ORDER_BY_UPDATE_TIME_DESC = " ORDER BY a.update_time desc ";
    private static final String SELECT_ALL = "select a.* ";
    private static final String SELECT_OPTIONS = "select id, name, url, method ";

    @Operation(summary = "分页获取HTTP接口列表")
    @Parameters({
        @Parameter(name = "keywords", description = "关键字", required = false),
        @Parameter(name = "cur", description = "当前页码", required = true),
        @Parameter(name = "limit", description = "每页数据量", required = true)
    })
    @TokenRequired
    @GetMapping(value = "/pages", produces = "application/json; charset=utf-8")
    public R<Page<HttpApi>> pages(
            HttpServletRequest request,
            @RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
            @RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
            @RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {
        
        StringBuilder sqlExceptSelect = new StringBuilder()
                .append(" from ").append(HttpApi.TABLE_NAME).append(" a WHERE 1=1 ");
                
        if (!StrKit.isBlank(keywords)) {
            sqlExceptSelect.append(" and (a.name like '%").append(keywords).append("%'")
                          .append(" or a.url like '%").append(keywords).append("%') ");
        }
        sqlExceptSelect.append(ORDER_BY_UPDATE_TIME_DESC);
        
		Page<HttpApi> page=HttpApi.dao.paginate(cur, limit, SELECT_ALL, sqlExceptSelect.toString());
		for(HttpApi httpApi:page.getList()) {
			httpApi.setIsRunning(dataTaskTimer.isRunning(httpApi.getId())?"1":"0");
		}
        return R.ok(page);
    }

    @Operation(summary = "保存HTTP接口")
    @Parameters({
        @Parameter(name = "httpApi", description = "HTTP接口信息", required = true)
    })
    @TokenRequired
    @Tx
    @PostMapping("/save")
    public R<HttpApi> save(HttpServletRequest request, @RequestBody HttpApi httpApi) {
        try {
            Date now = new Date(System.currentTimeMillis());
            String userId = getUserId(request);
            
            if (StrKit.notBlank(httpApi.getId())) {
                return updateHttpApi(httpApi, userId, now);
            } else {
                return createHttpApi(httpApi, userId, now);
            }
        } catch (Exception e) {
            return R.failed(e.getMessage());
        }
    }

    // 抽取更新方法
    private R<HttpApi> updateHttpApi(HttpApi httpApi, String userId, Date updateTime) {
        httpApi.setUpdateUserId(userId);
        httpApi.setUpdateTime(updateTime);
        return httpApi.update() ? R.ok(httpApi) : R.failed("更新失败！");
    }

    // 抽取创建方法
    private R<HttpApi> createHttpApi(HttpApi httpApi, String userId, Date createTime) {
        httpApi.setId(UuidUtil.getUUID());
        httpApi.setCreateUserId(userId);
        httpApi.setCreateTime(createTime);
        return httpApi.save() ? R.ok(httpApi) : R.failed("保存失败.");
    }

    @Operation(summary = "删除HTTP接口")
    @Parameters({
        @Parameter(name = "ids", description = "HTTP接口id集合(逗号分割)", required = true)
    })
    @DeleteMapping("/{ids}")
    @TokenRequired
    public R<String> delete(@PathVariable("ids") String ids) {
        if (StrKit.isBlank(ids)) {
            return R.failed("请选择需要删除的接口.");
        }
        
        try {
            for (String id : ids.split(",")) {
                if (!HttpApi.dao.deleteById(id)) {
                    return R.failed("删除失败: " + id);
                }
                dataTaskTimer.stopTask(id);
            }
            return R.ok();
        } catch (Exception e) {
            return R.failed("删除失败: " + e.getMessage());
        }
    }

    @Operation(summary = "测试HTTP接口")
    @Parameters({
        @Parameter(name = "id", description = "接口Id", required = true)
    })
    @PostMapping("/test/{id}")
    @TokenRequired
    public R<JSONObject> test(@PathVariable("id") String id) {
        try {
            HttpApi httpApi = HttpApi.dao.findById(id);
            if (httpApi == null) {
                return R.failed("接口不存在");
            }
            
            String paginationType = httpApi.getPaginationType();
            if(StrKit.equals("0", paginationType)) {
            	return  httpAPIImpl.execute(httpApi,new JSONObject());
            }else {
    			String pageField = httpApi.getPageField();
    			String pageSizeField = httpApi.getPageSizeField();
    			int pageSize = httpApi.getPageSize();
    			int pageNum = httpApi.getPageNum();
    			JSONObject params = new JSONObject();
    			params.put(pageField, pageNum);
    			params.put(pageSizeField, pageSize);
    			return  httpAPIImpl.execute(httpApi,params);
            }
        } catch (Exception e) {
            return R.failed("测试失败: " + e.getMessage());
        }
    }


    @Operation(summary = "获取HTTP接口下拉选项")
    @Parameters({
        @Parameter(name = "keywords", description = "关键字", required = false)
    })
    @TokenRequired
    @GetMapping("/options")
    public R<List<HttpApi>> options(
            HttpServletRequest request,
            @RequestParam(name = "keywords", required = false, defaultValue = "") String keywords) {
        
        try {
            StringBuilder sql = new StringBuilder()
                    .append(SELECT_OPTIONS)
                    .append(" from ").append(HttpApi.TABLE_NAME).append(" a ")
                    .append(" where 1=1");
            
            if (!StrKit.isBlank(keywords)) {
                sql.append(" and (name like '%").append(keywords).append("%'")
                   .append(" or url like '%").append(keywords).append("%'")
                   .append(" or method like '%").append(keywords.toUpperCase()).append("%')");
            }
            sql.append(ORDER_BY_UPDATE_TIME_DESC);
            return R.ok(HttpApi.dao.find(sql.toString()));
        } catch (Exception e) {
            return R.failed("获取选项失败: " + e.getMessage());
        }
    }
    
    @Operation(summary = "获取接口信息")
    @Parameters({
        @Parameter(name = "id", description = "接口Id", required = true)
    })
    @GetMapping("/{id}/info")
    @TokenRequired
    public R<HttpApi> getInfoById(@PathVariable("id") String id) {
        try {
            HttpApi httpApi = HttpApi.dao.findById(id);
            if (httpApi == null) {
                return R.failed("接口不存在");
            }
            return R.ok(httpApi);
        } catch (Exception e) {
            return R.failed("失败: " + e.getMessage());
        }
    }
    
	@Operation(summary = "启动HTTP客户端")
	@Parameters({ @Parameter(name = "id", description = "客户端Id", required = true) })
	@TokenRequired
	@PostMapping("/start/{id}")
	public R<String> start(@PathVariable("id") String id) {
		try {
			HttpApi httpApi=HttpApi.dao.findById(id);
	    	if (httpApi == null) {
	            return R.failed("HTTP数据不存在.");
	        }
			return dataTaskTimer.startTask(httpApi.getName(),"HTTP",id, httpApi.getFlow());
		} catch (Exception e) {
			return R.failed("启动失败: " + e.getMessage());
		}
	}

	@Operation(summary = "停止HTTP客户端")
	@Parameters({ @Parameter(name = "id", description = "客户端Id", required = true) })
	@TokenRequired
	@PostMapping("/stop/{id}")
	public R<Boolean> stop(@PathVariable("id") String id) {
		try {
			dataTaskTimer.stopTask(id);
			return R.ok(true);
		} catch (Exception e) {
			return R.failed("停止失败: " + e.getMessage());
		}
	}
    
    

}
